<?php
	class EnsembleDeCategories {
		
		var $selected;
		var $categories;
		var $racines;
		var $arborescence;
		var $niveaux;
		var $dejavu;
		var $ordrefinal;
		
		function EnsembleDeCategories($tri=true,$selected=NULL){
			$this->selected = $selected;
			$categories = $GLOBALS['PHPFoxEngine']->database->query("SELECT * FROM categories ORDER BY ca_titre ASC");
			$this->arborescence=array();$this->racines=array();$this->dejavu = array();$this->niveaux = array();$this->categories = array();
			while($categorie = mysql_fetch_assoc($categories)){
				$this->categories[$categorie['ca_id']] = $categorie;
				if($categorie['ca_surcategorie'] != 0) $this->arborescence[$categorie['ca_surcategorie']][] = $categorie['ca_id']; else $this->racines[] = $categorie['ca_id'];
				$this->dejavu[$categorie['ca_id']] = 0;
			}	
			if($tri)$this->trier();
		}
		
		function makeOptions(){
			$select='';
			foreach($this->categories as $value){
				$select .= ($this->selected == $value['ca_id'])? '<option selected="selected" id="'.$value['ca_id'].'" value="'.$value['ca_id'].'">'.$value['ca_titre'].'</option>':'<option id="'.$value['ca_id'].'" value="'.$value['ca_id'].'">'.$value['ca_titre'].'</option>';	
			}
			return $select;
		}
		
		function makeListeArborescence(){
			$liste = '<ul>';
			foreach($this->ordrefinal as $key => $value){
				$liste .= str_repeat('<ul>',$this->niveaux[$value]).'<li onClick="Javascript:convertToInputText(this)" class="arborescence"><input type="hidden" value="'.$this->categories[$value]['ca_id'].'" class="id"/><span class="titre">'.$this->categories[$value]['ca_titre'].'</span> - Prix : <span class="prix">'.$this->categories[$value]['ca_prix'].'</span><span class="button"></span></li>'.str_repeat('</ul>',$this->niveaux[$value]);
			}
			$liste.= '</ul>';
			return $liste;	
		}
		
		function trier(){
			$ordrefinal = array();
			$atraiter = array();
			foreach($this->racines as $key => $value){
				$niveau = 0;
				$this->niveaux[$value] = $niveau;
				$this->dejavu[$value] = 1;
				array_unshift($atraiter,$value);
				while(!empty($atraiter)){
					if(empty($this->arborescence[$atraiter[0]])){
						$this->niveaux[$atraiter[0]] = $niveau;
						$niveau--;
						array_unshift($ordrefinal,$atraiter[0]);
						array_shift($atraiter);
					}
					else
					{
						$sommet = $this->arborescence[$atraiter[0]][0];
						$niveau++;
						array_shift($this->arborescence[$atraiter[0]]);
						if($this->dejavu[$sommet] == 0){
							$this->dejavu[$sommet] = 1;
							array_unshift($atraiter,$sommet);					
						}
					}
				}
			}
			$this->ordrefinal = $ordrefinal;	
		}
	}
?>